﻿
/* 
 * Since 2008 - 2012
 */
package com.hh.bss.talent.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.base.BaseSpringController;
import com.hh.bss.common.page.Page;
import com.hh.bss.common.page.PageRequest;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvAttachment;
import com.hh.bss.talent.entity.CvAttachmentLog;
import com.hh.bss.talent.entity.CvTrainning;
import com.hh.bss.talent.service.CvAttachmentLogService;
import com.hh.bss.talent.service.CvAttachmentService;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.talent.vo.query.CvAttachmentQuery;
import com.hh.bss.util.StringHelper;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.ListRange;


@Controller
public class CvAttachmentController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private CvAttachmentService cvAttachmentService;
	
	@Autowired
	private CvAttachmentLogService  cvAttachmentLogService;
	
	private CvService cvService;
	
	private CvAttachment cvAttachment;
	java.lang.Integer id = null;
	private String[] items;

	
	
	/** 通过spring自动注入 */
	public void setCvAttachmentServiceImpl(CvAttachmentService service) {
		this.cvAttachmentService = service;
	}
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}
	
	
	
	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	public void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			result.put("failure", true);
			result.put("msg", "参数非法!");
		}
		try {
			CvAttachment cvAttachment = (CvAttachment) cvAttachmentService.getById(Integer.parseInt(id));
			if (cvAttachment != null) {
				result.put("data", cvAttachment);
				result.put("success", true);
				result.put("msg", "成功!");
			}

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * ExtGrid使用
	 * 列表
	 * @throws IOException
	 */
	public void list(HttpServletRequest request,HttpServletResponse response,CvAttachmentQuery cvAttachmentQuery) throws IOException
	{
		OnlineManager onlineManager=super.getOnlineManager(request, response);
		if (onlineManager!=null){
			OnlineUser onlineUser=onlineManager.getOnlineUser();
			cvAttachmentQuery.setOnlineUser(onlineUser);
		}
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		String cv_id = request.getParameter("cv_id");
		if (!StringHelper.isEmpty(cv_id))
			cvAttachmentQuery.setCvId(Integer.parseInt(cv_id));
		Page page = cvAttachmentService.findPage(cvAttachmentQuery);
		
		List<CvAttachment> CvAttachmentlist = (List) page.getResult();
		ListRange<CvAttachment> resultList = new ListRange<CvAttachment>();
		resultList.setRows(CvAttachmentlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}
	public String managerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
	    	
			return "forward:/jsp/talent/cvAttachment/cvAttachmentPage.jsp";
	}

	/**
	 * extGrid保存
	 * @throws IOException
	 */
	public void save(HttpServletRequest request,HttpServletResponse response,CvAttachment cvAttachment) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        //设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CvAttachment.class,"creator")) {
						try{com.hh.bss.util.BeanUtils.setProperty(cvAttachment,"creator",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CvAttachment.class,"createDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(cvAttachment,"createDt",new Date());}catch(Exception ex){}
			}
			
			String cv_id = request.getParameter("cv_id");
			if (!StringHelper.isEmpty(cv_id))
			  cvAttachment.setCvId(Integer.parseInt(cv_id));
			//cvAttachment.setCvId(Integer.parseInt(cv_id));
			//***开始上传文件处理****
			MultipartHttpServletRequest multipartRequest=null;
			MultipartFile multipartFile =null;
		       try{
		    	   multipartRequest = (MultipartHttpServletRequest) request;
		    	   multipartFile = multipartRequest.getFile("uploadFile");
		       }catch(Exception ex){ex.printStackTrace();}
		        
		       //multipart/form-data 提交模式，且提交了文件fileRes,则处理上传文件
		       if (multipartRequest!=null&&multipartFile!=null&&!multipartFile.isEmpty()){
		    	   cvAttachmentService.saveFile(multipartRequest, request, cvAttachment);			       
			       
		       }

		    //***上传文件处理结束****

		    //cvAttachmentService.updateCvResume(cvAttachment);
		    //List l = cvAttachmentService.findPage(cvAttachment);
		    //查询是否已经存在附件，如果没有附件 则更新简历提供者为当前登录用户
		    Integer count = cvAttachmentService.findAttachmentCountByCvId(cvAttachment.getCvId());
		    
		   
		    if(count != null && count == 0){
		    	Cv cv = cvService.getById(cvAttachment.getCvId());
		    	if(cv !=null){
		    		if(StringUtils.isEmpty(cv.getResumeInformer())){ //如果简历提供者为空才更新
		    			cv.setResumeInformer(cvAttachment.getCreator());
		    			cvService.update(cv);
		    		}
		    	}
		    	
		    }else if(count>0){
		    	 boolean f = cvAttachmentService.isUpdateResumeInformer(cvAttachment.getCvId());
		    	if(f){
		    		Cv cv = cvService.getById(cvAttachment.getCvId());
			    	if(cv !=null){
			    			cv.setResumeInformer(onlineManager.getOnlineUser().getUsername());
			    			cvService.update(cv);
			    	}
		    	}
		    }
		    
		    cvAttachment.setCreateDt(new Date());
			cvAttachmentService.save(cvAttachment);
			cvService.updateCvStatus(cvAttachment.getCvId());
			result.put("success", true);
			result.put("msg", "添加成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	public void down(HttpServletRequest request,HttpServletResponse response) throws IOException
 {

		String downfile = request.getParameter("downfile");
		InputStream fis = null;
		try {
			File file = new File(request.getSession().getServletContext().getRealPath(downfile));
			if (!file.exists())
				return;
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			logger.info("文件后缀名是:"+ext);
			if ("htm".equalsIgnoreCase(ext) || "html".equalsIgnoreCase(ext)) {
				response.sendRedirect(downfile);
			} else {
				// 以流的形式下载文件。
				fis = new BufferedInputStream(new FileInputStream(file));
				byte[] data = new byte[fis.available()];
				fis.read(data);
				fis.close();
				response.reset();
				response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
				response.addHeader("Content-Length", "" + data.length);
				response.setContentType("application/octet-stream;charset=UTF-8");
				OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
				outputStream.write(data);
				outputStream.flush();
				outputStream.close();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}

			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}
	}
	/**
	 * 人才附件下载
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void cvdown(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String downfile = request.getParameter("downfile");
		String id = request.getParameter("id");
		String cvId = request.getParameter("cvId");
		logger.info("人选附件下载开始:"+downfile);
		logger.info("Id:"+id);
		logger.info("cvId:"+cvId);
		
		if(StringUtils.isNotEmpty(downfile)){
			try {
				OnlineManager manager = super.getOnlineManager(request, response);
				if(manager != null){
					OnlineUser onlineUser = manager.getOnlineUser();
					if(onlineUser != null){
						if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(cvId)){
							CvAttachmentLog log = new CvAttachmentLog();
							if(id.startsWith("cr") || id.startsWith("jd")){
								log.setRefId(Integer.parseInt(id.substring(2)));
								log.setType(2);
							}else{
								log.setRefId(Integer.parseInt(id));
								log.setType(1);
							}
							log.setCvId(Integer.parseInt(cvId));
							log.setCreator(onlineUser.getUsername());
							log.setCreateDt(new Date());
							cvAttachmentLogService.save(log);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			response.sendRedirect(downfile);
		}
	}
	
	/**
	 * extGrid修改
	 * @throws IOException
	 */
	public void update(HttpServletRequest request,HttpServletResponse response,CvAttachment cvAttachment) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/html");
		try
		{
            CvAttachment oldcvAttachment = (CvAttachment)cvAttachmentService.getById(cvAttachment.getId());           
			bind(request,oldcvAttachment);
                        //设置修改用户和修改时间 
                        com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CvAttachment.class,"modifier")) {
						try{com.hh.bss.util.BeanUtils.setProperty(oldcvAttachment,"modifier",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CvAttachment.class,"modifiedDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(oldcvAttachment,"modifiedDt",new Date());}catch(Exception ex){}
				}
			String cv_id = request.getParameter("cv_id");
			//cvAttachment.setCvId(Integer.parseInt(cv_id));
			if (!StringHelper.isEmpty(cv_id))
			  oldcvAttachment.setCvId(Integer.parseInt(cv_id));
			//***开始上传文件处理****
			MultipartHttpServletRequest multipartRequest=null;
			MultipartFile multipartFile =null;
		       try{
		    	   multipartRequest = (MultipartHttpServletRequest) request;
		    	   multipartFile = multipartRequest.getFile("uploadFile");
		       }catch(Exception ex){ex.printStackTrace();}
		        
		       //multipart/form-data 提交模式，且提交了文件fileRes,则处理上传文件
		       
		       if (multipartRequest!=null&&multipartFile!=null&&!multipartFile.isEmpty()){		    	   			       
			       cvAttachmentService.saveFile(multipartRequest, multipartRequest, oldcvAttachment);	
		       }

		    //***上传文件处理结束****

			cvAttachmentService.update(oldcvAttachment);
			result.put("success", true);
			result.put("msg", "修改成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	
	/**
	 * extGrid删除
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			for (int i = 0; i < idarray.length; i++)
			{
				java.lang.Integer id = new java.lang.Integer((String)idarray[i]);
				//查记录
				CvAttachment cvAttachment=(CvAttachment)cvAttachmentService.getById(id);				
				Integer cvId=null;
				if (cvAttachment!=null) cvId=cvAttachment.getCvId();
				cvAttachmentService.removeById(id);
				
                if (cvId!=null){
                	//System.out.println("sdfsdfdsfds--------------------");
                	cvService.updateCvStatus(cvId);
				}
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	/**
	 * 检查是否存在附件
	 * @param request
	 * @param response
	 */
	public void checkattachment(HttpServletRequest request,HttpServletResponse response){
		String cvId = request.getParameter("cvId");
		Map<String, Object> result = new HashMap<String, Object>();
		if(cvId !=null && !"".equals(cvId)){
			Integer count = cvAttachmentService.findAttachmentCountByCvId(Integer.parseInt(cvId));
			if(count > 0){
				result.put("success", true);
			}
		}
		result.put("failure", true);
		outJson(response,result);
	}
	
	
}
